package com.app.android.coliy.ui.activity;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.android.coliy.R;
import com.app.android.coliy.adapter.SearchDeviceListAdapter;
import com.app.android.coliy.bean.LocalFileInfo;
import com.app.android.coliy.interface_.CommCallBack;
import com.feasycom.bean.BluetoothDeviceWrapper;
import com.feasycom.controler.FscSppApi;
import com.feasycom.controler.FscSppApiImp;
import com.feasycom.controler.FscSppCallbacksImp;

import org.litepal.crud.DataSupport;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2018/6/20.
 */

public class BlueToothListActivity_New extends BaseActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String fileName = getIntent().getStringExtra("fileName");
        if (!TextUtils.isEmpty(fileName)) {
            List<LocalFileInfo> localFileList = DataSupport.findAll(LocalFileInfo.class);
            if (localFileList != null) {
                for (int i = 0; i < localFileList.size(); i++) {
                    if (fileName.equals(localFileList.get(i).filename)) {
                        localFileInfo = localFileList.get(i);
                        break;
                    }
                }
            }
        }
        setContentView(R.layout.activity_bluetooth_new);
        initView();
        timerUI = new Timer();
        taskUI = new UITimerTask(new WeakReference<BlueToothListActivity_New>((BlueToothListActivity_New) mContext));
        timerUI.schedule(taskUI, 100, 250);
    }

    LocalFileInfo localFileInfo;
    FscSppApi fscSppApi;
    List<BluetoothDeviceWrapper> deviceWrapperList = new ArrayList<>();
    Queue<BluetoothDeviceWrapper> deviceQueue = new LinkedList<BluetoothDeviceWrapper>();
    private Timer timerUI;
    private TimerTask taskUI;
    private static String[] PERMISSIONS_LOCATION = {
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.BLUETOOTH_PRIVILEGED
    };
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
            Manifest.permission.BLUETOOTH_PRIVILEGED
    };
    private final int REQUEST_LOCATION = 3;
    private final int REQUEST_FILE = 4;


    RecyclerView recyclerview;
    SearchDeviceListAdapter adapter;

    @Override
    protected void onResume() {
        super.onResume();
        fscSppApi = FscSppApiImp.getInstance((Activity) mContext);
        fscSppApi.initialize();
        fscSppApi.setCallbacks(new FscSppCallbacksImp() {
            @Override
            public void sppDeviceFound(BluetoothDeviceWrapper device, int rssi) {
//                Log.i("info:"+ info.getName());
//                boolean hasAdded = false;
//                for (int i = 0; i < deviceWrapperList.size(); i++) {
//                    if (deviceWrapperList.get(i).getAddress().equals(info.getAddress())) {
//                        hasAdded = true;
//                        break;
//                    }
//                }
//                if (!hasAdded) {
//                    if (!TextUtils.isEmpty(info.getIncompleteServiceUUIDs_128bit())) {
//                        String uuid = info.getIncompleteServiceUUIDs_128bit().replace(" ", "").toLowerCase();
//                        String targetUUID = Constants.uuid.replace("-", "").toLowerCase();
//                        Log.i("uuid:"+ uuid);
//                        if (uuid.equals(targetUUID)) {
//                            deviceWrapperList.add(info);
//                            adapter.notifyDataSetChanged();
//                        }
//                    }
//                }
                if (deviceQueue.size() < 10) {
                    deviceQueue.offer(device);
                }
            }

            public void startScan() {
                startRefrsh();
            }

            public void stopScan() {
                stopRefrsh();
            }
        });
        int permissionLocation = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        int permissionFile = ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_LOCATION,
                    REQUEST_LOCATION
            );
        } else if (permissionFile != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_FILE
            );
        }
        startScan();
        timerUI = new Timer();
        taskUI = new UITimerTask(new WeakReference<BlueToothListActivity_New>((BlueToothListActivity_New) mContext));
        timerUI.schedule(taskUI, 100, 250);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != timerUI) {
            timerUI.cancel();
            timerUI = null;
        }
        if (null != taskUI) {
            taskUI.cancel();
            taskUI = null;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        /**
         * fscSppApi.stopScan()  will  release the resources of broadcastReceiver
         */
        fscSppApi.stopScan();
//        fscBleCentralApi.stopScan();
        if (null != timerUI) {
            timerUI.cancel();
            timerUI = null;
        }
        if (null != taskUI) {
            taskUI.cancel();
            taskUI = null;
        }
    }

    //初始化控件
    private void initView() {
        setTitle(getString(R.string.bluetooth_title));    //设置标题
        setLeftImgClickListener();  //设置左键返回
        setRightImgClickListener(R.drawable.ico_refresh);

        recyclerview = findViewById(R.id.recyclerview);
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        adapter = new SearchDeviceListAdapter(mContext,callBack);
        recyclerview.setAdapter(adapter);

    }

    CommCallBack callBack = new CommCallBack() {
        @Override
        public void onResult(Object obj) {
            BluetoothDeviceWrapper info = (BluetoothDeviceWrapper) obj;
            if (localFileInfo != null) {
                try {
//                    Bitmap bitmap = BitmapUtil.getSmallBitmap(localFileInfo.snapshot);
//                    Print_Dialog1 dialog = new Print_Dialog1(mContext);
//                    dialog.setData(bitmap, info);
//                    dialog.show();
                    Intent intent = new Intent(mContext,PrintActivity.class);
                    intent.putExtra("snapshot",localFileInfo.snapshot);
                    intent.putExtra("deviceWrapper",info);
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    private final int ENABLE_BT_REQUEST_ID = 2;

    public void startScan() {
        if (fscSppApi.isBtEnabled() == false) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, ENABLE_BT_REQUEST_ID);
        }
        fscSppApi.startScan(8000);
        deviceWrapperList.clear();
        adapter.notifyDataSetChanged();
    }

    //点击事件
    @Override
    public void onClick(View view) {
        super.onClick(view);
        Intent intent;
        switch (view.getId()) {
            case R.id.public_title_right_img:
                startScan();
                break;
        }
    }

    //开始旋转动画
    private void startRefrsh() {
        ImageView iv = findViewById(R.id.public_title_right_img);
        RotateAnimation ta = new RotateAnimation(0, 360, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
        ta.setDuration(500);
        ta.setInterpolator(new LinearInterpolator());
        ta.setRepeatCount(-1);
        iv.startAnimation(ta);
    }

    //结束旋转动画
    private void stopRefrsh() {
        ImageView iv = findViewById(R.id.public_title_right_img);
        iv.clearAnimation();
    }


    class UITimerTask extends TimerTask {
        private WeakReference<BlueToothListActivity_New> activityWeakReference;

        public UITimerTask(WeakReference<BlueToothListActivity_New> activityWeakReference) {
            this.activityWeakReference = activityWeakReference;
        }

        @Override
        public void run() {
            activityWeakReference.get().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    activityWeakReference.get().getAdapter().addDevice(activityWeakReference.get().getDeviceQueue().poll());
                    activityWeakReference.get().getAdapter().notifyDataSetChanged();
                }
            });
        }
    }

    public SearchDeviceListAdapter getAdapter() {
        return adapter;
    }

    public Queue<BluetoothDeviceWrapper> getDeviceQueue() {
        return deviceQueue;
    }

}
